/*
 * @Author: yuanxiaohu
 * @Date: 2025-06-21 22:08:44
 * @LastEditors: yuanxiaohu
 * @LastEditTime: 2025-06-22 00:02:22
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \wine-trend-hui-18\cloudfunctions\formSettings\getFormSettings\index.js
 */
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
    const { inviteRole, _openid } = event.data
    const db = cloud.database()

    try {
        // 1. 查询用户配置
        const res = await db.collection('form_settings')
            .where({ _openid, inviteRole })
            .get()

        // 2. 如果找到配置则返回，否则返回默认配置
        if (res.data.length > 0) {
            return {
                success: true,
                formOption: res.data[0].formOption,
                // formOption: inviteRole === 1 ? res.data[0].formOption : null,
                // 为了兼容您的前端代码，同时返回 agentFormOption
                // agentFormOption: inviteRole === 2 ? res.data[0].formOption : null
            }
        } else {
            // 返回默认配置
            const defaultConfig = getDefaultConfig(inviteRole)
            return {
                success: true,
                formOption: defaultConfig,
            }
        }
    } catch (err) {
        console.error('获取配置失败:', err)
        return {
            success: false,
            message: '获取配置失败',
            error: err
        }
    }
}

// 获取默认配置的函数
function getDefaultConfig(inviteRole) {
    if (inviteRole === 1) {
        return {
            applyTime: true,
            applyNickName: true,
            applyName: true,
            applyPhone: true,
            applyWx: true,
            applyMsg: true
        }
    } else if (inviteRole === 2) {
        return {
            userName: true,
            contact: true,
            phone: true,
            email: true,
            address: true,
            business: true,
            saleChannel: true,
            businessLicense: true,
            foodBusinessLicense: true,
            idCard: true
        }
    }
    return {}
}